package com.invest.infra.mvc.utils;

import com.google.gson.Gson;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

/**
 * <p>注释</p>
 *
 * @author yuyizhao
 * @version v0.1 2016/3/2 Exp
 */
public class MvcResultUtils {

    public static MvcResult populate(BindingResult result){

        MvcResult myResult = new MvcResult();

        if(result.hasFieldErrors()){
            for(FieldError item : result.getFieldErrors()){
                myResult.addFieldError(item.getField(),item.getDefaultMessage());
            }
        }

        if(result.hasGlobalErrors()){
            for(ObjectError item : result.getGlobalErrors()){
                myResult.addGlobalError(item.getDefaultMessage());
            }
        }
        return myResult;

    }

    public static String toJsonStr(MvcResult result){
        return new Gson().toJson(result);
    }
}
